package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.UserCourseTimeStatus;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SpokenTeacher;
import com.ruoyi.system.domain.SpokenTeacherCourseTime;
import com.ruoyi.system.domain.SpokenUserCourseTime;
import com.ruoyi.system.mapper.SpokenTeacherMapper;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class SpokenTeacherServiceImpl implements ISpokenTeacherService {

    @Autowired
    SpokenTeacherMapper teacherMapper;

    @Autowired
    ISysUserService sysUserService;

    @Autowired
    ISpokenTeacherTagService teacherTagService;

    @Autowired
    ISpokenTeacherCourseTimeService teacherCourseTimeService;

    @Autowired
    ISpokenUserCourseTimeService userCourseTimeService;

    @Override
    public List<SpokenTeacher> selectList(SpokenTeacher teacher) {
        List<SpokenTeacher> spokenTeachers = teacherMapper.selectList(teacher);
        for (SpokenTeacher t: spokenTeachers) {
            List<String> tagIds = Arrays.asList(t.getTagIds().split(","));
            String tagName = "";
            for (String tagId: tagIds) {
                tagName += teacherTagService.selectById(Long.valueOf(tagId)).getTagName() + ",";
            }
            String s = tagName.substring(0, tagName.length() - 1);
            t.setTagName(s);
        }
        return spokenTeachers;
    }

    /**
     * 添加教师
     * @param teacher
     * @return
     */
    @Transactional
    @Override
    public int insert(SpokenTeacher teacher) {
        // 添加用户主表
        SysUser sysUser = teacher.getSysUser();
        sysUser.setRoleId(100l);   // 角色：移动端用户
        sysUser.setUserType("02");  // 用户类型：教师
        sysUser.setStatus(UserStatus.OK.getCode());
        sysUser.setDelFlag("0");
        sysUser.setPhonenumber(teacher.getSysUser().getUserName());
        sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        sysUser.setCreateTime(new Date());
        sysUserService.insertUser(sysUser);

        teacher.setTeacherId(sysUser.getUserId());
        // 添加教师表
        teacherMapper.insert(teacher);
        // 添加关联的课程表及所选的星期
        List<SpokenTeacherCourseTime> teacherCourseTime = teacher.getTeacherCourseTime().stream()
                .filter(item -> !StringUtils.isEmpty(item.getDays())).collect(Collectors.toList());
        for (SpokenTeacherCourseTime spokenTeacherCourseTime : teacherCourseTime) {
            spokenTeacherCourseTime.setTeacherId(teacher.getTeacherId());
        }

        return teacherCourseTimeService.insert(teacherCourseTime);
    }

    @Override
    public SpokenTeacher selectById(Long teacherId) {
        SpokenTeacher spokenTeacher = teacherMapper.selectById(teacherId);
        List<String> tagIds = Arrays.asList(spokenTeacher.getTagIds().split(","));
        String tagName = "";
        for (String tagId: tagIds) {
            tagName += teacherTagService.selectById(Long.valueOf(tagId)).getTagName() + ",";
        }
        String s = tagName.substring(0, tagName.length() - 1);
        spokenTeacher.setTagName(s);
        List<SpokenTeacherCourseTime> spokenTeacherCourseTimes = teacherCourseTimeService.selectByTeacherId(spokenTeacher.getTeacherId());
        spokenTeacher.setTeacherCourseTime(spokenTeacherCourseTimes);
        return spokenTeacher;
    }

    @Override
    public int update(SpokenTeacher teacher) {
        sysUserService.updateUser(teacher.getSysUser());
        return teacherMapper.update(teacher);
    }

    @Override
    public int updateMeetingInfo(SpokenTeacher teacher) {
        return teacherMapper.updateMeetingInfo(teacher);
    }

    @Transactional
    @Override
    public int delete(Long teacherId) {
        SpokenUserCourseTime userCourseTime = new SpokenUserCourseTime();
        userCourseTime.setTeacherId(teacherId);
        List<SpokenUserCourseTime> select = userCourseTimeService.select(userCourseTime);
        // 过滤出课时状态为正常的数据
        select = select.stream().filter(item -> item.getStatus().equals(UserCourseTimeStatus.NORMAL.getCode())).collect(Collectors.toList());
        if(select.size() > 0){
            throw new ServiceException("当前教师存在未消课课时，无法删除");
        }
        // 删除教师
        teacherMapper.delete(teacherId);
        return sysUserService.deleteUserById(teacherId);
    }

    @Override
    public int selectCountByTagId(Long tagId) {

        return teacherMapper.selectCountByTagId(tagId);
    }

    @Override
    public boolean selectCountByCourseId(Long courseId) {
        Integer count = teacherMapper.checkCourseIsExist(courseId);
        return count > 0;
    }

    /**
     * 根据年月查询当月教师没有课的日期
     * @param teacherId
     * @param date
     * @return
     */
    public List<String> selectDisableDate(Long teacherId, String date){
        // 查询教师周几有课
        List<SpokenTeacherCourseTime> teacherCourseTime = selectById(teacherId).getTeacherCourseTime();
        Set weeks = new HashSet();
        for (SpokenTeacherCourseTime spokenTeacherCourseTime : teacherCourseTime) {
            List days = Arrays.asList(spokenTeacherCourseTime.getDays().split(","));
            weeks.addAll(days);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        int year = Integer.valueOf(date.split("-")[0]);
        int month = Integer.valueOf(date.split("-")[1]);
        Calendar c = Calendar.getInstance();
        int currentYear = c.get(Calendar.YEAR);
        int currentMonth = c.get(Calendar.MONDAY);
        int currentDate = c.get(Calendar.DATE);
        Date startDate = null;
        Date endDate = null;
        // 查询本月
        if(year == currentYear && month == currentMonth + 1){
            // 开始日期
            c.set(currentYear, currentMonth, currentDate + 1);
            startDate = c.getTime();
            // 结束日期
            int actualMaximum = c.getActualMaximum(Calendar.DAY_OF_MONTH);
            c.set(currentYear, currentMonth, actualMaximum);
            endDate = c.getTime();
        }
        // 其他月
        else{
            // 开始日期
            c.set(year, month - 1, 1);
            startDate = c.getTime();
            // 结束日期
            c.add(Calendar.MONDAY, 1);
            c.add(Calendar.DATE, -1);
            endDate = c.getTime();
        }
        Calendar day = Calendar.getInstance();
        day.setTime(startDate);
        List<String> disableDate = new ArrayList();
        for(int i = startDate.getDate(); i <= endDate.getDate(); i ++){
            int dayOfWeek = day.get(Calendar.DAY_OF_WEEK);
            if(dayOfWeek == 1){
                dayOfWeek = 7;
            }else{
                dayOfWeek -= 1;
            }
            // 当前日期对应的星期未选择
            if(!weeks.contains(String.valueOf(dayOfWeek))){
                disableDate.add(sdf.format(day.getTime()));
            }
            day.add(Calendar.DATE, 1);
        }
        return disableDate;
    }

    /**
     * 根据日期、教师ID查询对应时间段
     */
    @Override
    public List<SpokenTeacherCourseTime> selectTimes(Long teacherId, String date){
        // 根据日期获取星期数
        List<Integer> dateList = Arrays.stream(date.split("-")).map(item -> Integer.valueOf(item)).collect(Collectors.toList());
        Calendar c = Calendar.getInstance();
        c.set(dateList.get(0), dateList.get(1) - 1, dateList.get(2));
        int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
        if(dayOfWeek == 1){
            dayOfWeek = 7;
        }else{
            dayOfWeek -= 1;
        }
        // 根据教师ID与星期查询教师选择的课时
        List<SpokenTeacherCourseTime> spokenTeacherCourseTimes = teacherCourseTimeService.selectByTeacherIdAndDay(teacherId, String.valueOf(dayOfWeek));

        for (SpokenTeacherCourseTime spokenTeacherCourseTime : spokenTeacherCourseTimes) {
            // 获取对应教师、对应日期、对应课时的状态
            SpokenUserCourseTime spokenUserCourseTime = new SpokenUserCourseTime();
            spokenUserCourseTime.setChooseDate(LocalDate.parse(date));   // 日期
            spokenUserCourseTime.setTimeId(spokenTeacherCourseTime.getCourseTimeId());  // 时间段ID
            spokenUserCourseTime.setTeacherId(teacherId);   // 教师ID
            List<SpokenUserCourseTime> selectList = userCourseTimeService.select(spokenUserCourseTime);
            // 状态为：正常、消课、待支付的不可以选择
            List statusList = new ArrayList();
            statusList.add(UserCourseTimeStatus.NORMAL.getCode());
            statusList.add(UserCourseTimeStatus.CANCEL_LESSON.getCode());
            statusList.add(UserCourseTimeStatus.PRE_PAY.getCode());
            selectList = selectList.stream().filter(item -> statusList.contains(item.getStatus())).collect(Collectors.toList());
            // 对应教师、对应日期、对应课时已被选择
            if(selectList.size() > 0){
                spokenTeacherCourseTime.setIsChoosed(true);
            }else{
                spokenTeacherCourseTime.setIsChoosed(false);
            }
        }

        return spokenTeacherCourseTimes;
    }

    @Override
    public Integer selectTeacherCount(String startDate, String endDate) {
        return teacherMapper.selectTeacherCount(startDate, endDate);
    }
}
